from django.shortcuts import render, redirect, reverse
from .forms import LoginForm, RegisterForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from utils.captcha.hycaptcha import Captcha
from django.http import HttpResponse
from io import BytesIO
# from utils.aliyunsdk import aliyun
from .models import User
# from apps.forms import FormsMixin
from utils import restful


# from django.forms.utils import ErrorDict


# Create your views here.

def login_view(request):
    if request.method == 'GET':
        return render(request, 'auth/login.html')
    elif request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get('telephone')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = authenticate(request, username=telephone, password=password)
            if user:
                login(request, user)
                if remember:
                    # 如果设置过期时间为none, 则使用默认过期时间, 默认过期时间为14天
                    request.session.set_expiry(None)
                else:
                    # 如果设置过期时间为0, 则关闭浏览器以后就会结束
                    request.session.set_expiry(0)
                return redirect(reverse('news:index'))
            else:
                # 提示错误消息
                messages.info(request, '用户名或密码错误!')
                return redirect(reverse('xfzauth:login'))
        else:
            # 提示错误消息
            messages.info(request, '表单验证失败!')
            return redirect(reverse('xfzauth:login'))


def logout_view(request):
    logout(request)
    return redirect(reverse('news:index'))


# Form表单版本注册代码
# def register_view(request):
#     if request.method == 'GET':
#         return render(request, 'auth/register.html')
#     if request.method == 'POST':
#         form = RegisterForm(request.POST)
#         if form.is_valid() and form.validate_data(request):
#             # 数据正确,完成注册
#             telephone = form.cleaned_data.get('telephone')
#             username = form.cleaned_data.get('username')
#             password = form.cleaned_data.get('password1')
#             email = form.cleaned_data.get('email', None)
#
#             user = User.objects.create_user(telephone=telephone, username=username, password=password, email=email)
#
#             # 完成登陆
#             login(request, user)
#             request.session['user'] = user.username
#             return redirect(reverse('news:index'))
#         else:
#             message_list = form.get_errors()
#             if message_list:
#                 for message in message_list:
#                     messages.info(request, message)
#             else:
#                 messages.info(request, '表单验证失败!')
#             return redirect(reverse('xfzauth:register'))
#         return redirect(reverse('xfzauth:login'))


# ajax请求版本注册代码
def register_view(request):
    if request.method == 'GET':
        return render(request, 'auth/register.html')
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid() and form.validate_data(request):
            # 数据正确,完成注册
            telephone = form.cleaned_data.get('telephone')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            email = form.cleaned_data.get('email', None)

            user = User.objects.create_user(telephone=telephone, username=username, password=password, email=email)

            # 完成登陆
            login(request, user)
            request.session['user'] = user.username
            return restful.ok()
        else:
            messages = form.get_errors()
            return restful.params_error(messages)


def img_captcha(request):
    text, image = Captcha.gene_code()
    # image不是一个HttpResponse可识别的对象, 因此需要将image变成一个数据流才能放入HttpResponse上
    out = BytesIO()  # BytesIO相当于一个管道,可以哟过来存储字节流的
    image.save(out, 'png')
    out.seek(0)  # 将文件指针设置到0的位置

    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()

    # 保存验证码到session中, 用于前台数据校验
    print('图形验证码是:%s' % text)
    request.session['img_captcha'] = text
    return response


def sms_captcha(request):
    code = Captcha.gene_text()
    telephone = request.GET.get('telephone')
    if not telephone:
        telephone = request.POST.get('telephone')

    # 发送短信代码如下, 因为现在是测试, 故注释下面代码, 模拟即可
    # result = aliyun.send_sms(telephone, code=code)
    # print('短信发送结果是%s' % result)

    print('手机验证码是:%s' % code)
    # 保存验证码到session中, 用于前台数据校验
    request.session['sms_captcha'] = code

    return HttpResponse('短信发送成功!')
